import 'dart:convert';
import 'dart:io';
import 'dart:ui';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:freedom/const/game_const.dart';
import 'package:freedom/entity/restful.dart';
import 'package:freedom/entity/user_entity_info.dart';
import 'package:freedom/page/game_index.dart';
import 'package:freedom/util/api_router.dart';
import 'package:freedom/util/cache_util.dart';
import 'package:freedom/util/customer_dialog.dart';
import 'package:freedom/util/data_type.dart';
import 'package:freedom/util/encrypt_helper.dart';
import 'package:freedom/util/http.dart';
import 'package:freedom/util/navigator_provider.dart';
import 'package:freedom/widget/bubble_widget.dart';
import 'package:freedom/widget/dialog/verification_widget.dart';
import 'package:freedom/widget/i_text_filed.dart';
import 'package:freedom/util/reg_exp_constant.dart';
import 'package:freedom/page/common/user_agreement.dart';
import 'package:provider/provider.dart';

class UserLoginWidget extends StatefulWidget {
  @override
  _UserLoginWidgetState createState() => _UserLoginWidgetState();
}

class _UserLoginWidgetState extends State<UserLoginWidget> {
  GlobalKey<ScaffoldState> globalKey = GlobalKey<ScaffoldState>();

  TextFiledValidata? _userNameVlidata;
  TextFiledValidata? _pwdVlidata;
  //第一部分 第一层 渐变背景
  Container buildBackground() {
    return Container(
      width: double.infinity,
      height: double.infinity,
      decoration: BoxDecoration(
        //线性渐变
        gradient: LinearGradient(
          //渐变角度
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          //渐变颜色组
          colors: [
            Colors.lightBlue.withOpacity(0.3),
            Colors.lightBlueAccent.withOpacity(0.3),
            Colors.blue.withOpacity(0.3),
          ],
        ),
      ),
    );
  }

//第三部分 高斯模糊
  Widget buildBlureWidget() {
    return BackdropFilter(
      filter: ImageFilter.blur(sigmaX: 0.3, sigmaY: 0.3),
      child: Container(
        color: Colors.grey.withOpacity(0.2),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    // 同步加载 麻将资源资源
    _userNameVlidata = TextFiledValidata.init(
        show: false, tips: "账号不合法", paretten: RegExpConstant.userName);
    _pwdVlidata = TextFiledValidata.init(
        show: false, tips: "请输入密码", paretten: "^.{5,10}");
    /* WidgetsBinding.instance.addPostFrameCallback((context) {
      Future.delayed(Duration(milliseconds: 500), () {
        showDialog<Null>(
            context: this.context,
            barrierDismissible: false,
            builder: (BuildContext context) {
              return UserAgreement();
            });
      });
    });*/
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
      child: Stack(
        children: [
          // 背景
          Positioned(
              child: Container(
            width: double.infinity,
            height: double.infinity,
            child: Image.asset(
              "assets/images/mahjong/background/login_bg.jpg",
              fit: BoxFit.cover,
            ),
          )),
          Align(
              alignment: Alignment(-0.8, -0.8),
              child: Container(
                alignment: Alignment.center,
                height: ScreenUtil().screenWidth / 4 / 4.5,
                width: ScreenUtil().screenWidth / 4,
                child: Image.asset(
                  "assets/images/logo/logo.png",
                  fit: BoxFit.cover,
                ),
              )),
          BubbleWidget(
            bubbleCout: 3,
          ),
          buildBlureWidget(),
          Positioned(
            bottom: MediaQuery.of(context).size.height / 8,
            left: MediaQuery.of(context).size.width / 3,
            right: MediaQuery.of(context).size.width / 3,
            child: Column(
              children: [
                ITextFiled(
                  400.w,
                  60.h,
                  hintText: "请输入账号",
                  defaultStr: "",
                  preIcon: Icons.email,
                  textFiledValidata: _userNameVlidata,
                ),
                SizedBox(
                  height: MediaQuery.of(context).size.height / 8 / 2,
                ),
                ITextFiled(
                  400.w,
                  60.h,
                  hintText: "密码",
                  defaultStr: "",
                  obscureText: true,
                  preIcon: Icons.fingerprint,
                  textFiledValidata: _pwdVlidata,
                ),
                SizedBox(
                  height: MediaQuery.of(context).size.height / 8 / 2,
                ),
                Column(
                  children: [
                    Container(
                        color: Colors.blue.withOpacity(0.8),
                        width: MediaQuery.of(context).size.width / 3,
                        height: MediaQuery.of(context).size.height / 10,
                        child: TextButton(
                          child: Text(
                            "登录",
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 20.sp,
                                height: 1.0),
                          ),
                          onPressed: () {
                            if (_userNameVlidata!.check() &&
                                _pwdVlidata!.check()) {
                              CustomerDialog.showGamingDialog(
                                  (cancelFunc) => VerificationWidget(
                                          callBack: (data) async {
                                        String decodePwd =
                                            await EncryptHelper.encode(
                                                _pwdVlidata!.value!);
                                        UserEntityInfo userInfo =
                                            UserEntityInfo(
                                                verificationMode: data,
                                                sysUser: SysUser.init(
                                                    _userNameVlidata!.value,
                                                    decodePwd));
                                        Http.getInstance().request<Restful>(
                                            ApiRouter.login,
                                            type: RequestEnum.POST,
                                            contentType: ContentType.json,
                                            showLoading: true,
                                            loadingMsg: "登录中...",
                                            data: userInfo.toString(),
                                            success: (data) {
                                          var loginUser =
                                              Provider.of<UserEntityInfo>(
                                                  context,
                                                  listen: false);
                                          loginUser.updateInfo(
                                              UserEntityInfo.fromJson(
                                                  asT<Map<String, dynamic>>(
                                                      data.body)));
                                          CacheUtil.preferencesInstance!
                                              .setString(CacheConst.userInfo,
                                                  json.encode(data.body));
                                          NavigatorProvider.pushAndRemoveUntil(
                                              const GameIndex());
                                        }, error: (data) {
                                          BotToast.showText(text: data.msg!);
                                        });
                                      }),
                                  groupKey: CustomerDialog.verificationCode);
                            } else {
                              setState(() {});
                            }
                          },
                        )),
                  ],
                )
              ],
            ),
          ),
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: Container(
              alignment: Alignment.center,
              color: Colors.black.withOpacity(0.2),
              height: MediaQuery.of(context).size.height / 12,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Text(
                    "App V1.1 Res V1.1.1.1",
                    style: TextStyle(color: Colors.white, fontSize: 20.sp),
                  ),
                  Text("抵制不良游戏,拒绝盗版游戏,注意自我保护,谨防上当受骗;",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 15.sp,
                      )),
                ],
              ),
            ),
          ),
          Align(
            alignment: const Alignment(0, 0.95),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  "找回密码",
                  style: TextStyle(color: Colors.black, fontSize: 18.sp),
                ),
                SizedBox(
                  height: 40.h,
                  child: Container(
                    margin:
                        EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.h),
                    height: 40.h,
                    width: 1,
                    child: const DecoratedBox(
                      decoration: BoxDecoration(color: Colors.black),
                    ),
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Text(
                      "登录即同意",
                      style: TextStyle(fontSize: 18.sp, color: Colors.black),
                    ),
                    InkWell(
                      child: Text(
                        "<<逍遥棋牌>>",
                        style: TextStyle(
                            decoration: TextDecoration.underline,
                            fontSize: 18.sp,
                            color: Colors.orange),
                      ),
                      onTap: () {
                        showDialog<Null>(
                            context: context,
                            barrierDismissible: false,
                            builder: (BuildContext context) {
                              return UserAgreement();
                            });
                      },
                    ),
                    Text(
                      "用户协议",
                      style: TextStyle(fontSize: 18.sp, color: Colors.black),
                    )
                  ],
                ),
                SizedBox(
                  height: 40.h,
                  child: Container(
                    margin:
                        EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.h),
                    height: 40.h,
                    width: 1,
                    child: DecoratedBox(
                      decoration: BoxDecoration(color: Colors.white),
                    ),
                  ),
                ),
                InkWell(
                  child: Text("注册新用户",
                      style: TextStyle(color: Colors.black, fontSize: 18.sp)),
                  onTap: () {
                    CustomerDialog.showText("暂未开放?");
                    /* showDialog<Null>(
                        context: context,
                        barrierDismissible: false,
                        builder: (BuildContext context) {
                          return RegisterAccount();
                        }); */
                  },
                )
              ],
            ),
          )
        ],
      ),
    ));
  }
}
